import { useRef, useState } from "react";
import { Table, Button, Image, Avatar, Popconfirm, message } from "antd";
import { PageContainer } from "@ant-design/pro-layout";
import ProForm, {
  ModalForm,
  ProFormDateTimeRangePicker,
  ProFormText,
  ProFormDigit,
  ProFormRadio,
  ProFormDependency,
  ProFormTextArea,
} from "@ant-design/pro-form";
import useCommonTable from "@/hooks/useCommonTable";

import {
  fetchList,
  add,
  update,
  remove,
  fetchRegisterList,
  updateStatus,
} from "@/api/paint";
import UploadFile from "@/components/UploadFile";
import { typeNumOptions, disableStatusOptions } from "@/const";
import moment from "moment";
import { ProTable } from "@ant-design/pro-components";

export default () => {
  const renderRegisterRecordModal = (row) => {
    const columns = [
      {
        title: "报名人",
        dataIndex: "userRealName",
        render: (_, record) => {
          return (
            <div>
              <Avatar size={40} src={record.avatar} />
              <span style={{ margin: "0 10px" }}>
                {record.userRealName || record.userNickName}
              </span>
              <span>{record.mobile}</span>
            </div>
          );
        },
      },
      {
        title: "报名时间",
        dataIndex: "createTime",
      },
    ];
    return (
      <ModalForm
        key="registerRecord"
        layout="horizontal"
        title="报名记录"
        width={600}
        submitter={false}
        trigger={<Button type="primary">报名记录</Button>}
      >
        <ProTable
          params={{
            starPaintId: row.id,
          }}
          search={false}
          options={false}
          columns={columns}
          request={fetchRegisterList}
        />
      </ModalForm>
    );
  };

  const columns = [
    {
      title: "标题",
      dataIndex: "title",
      search: false,
      width: 200,
    },
    {
      title: "封面",
      dataIndex: "cover",
      search: false,
      width: 100,
      render: (_, record) => {
        return <Image width={50} height={50} src={record.cover} />;
      },
    },
    {
      title: "人数上限",
      width: 100,
      dataIndex: "limitNum",
      search: false,
    },
    {
      title: "支付积分",
      dataIndex: "consumePoints",
      search: false,
      width: 100,
    },
    {
      title: "获得积分",
      dataIndex: "obtainPoints",
      search: false,
      width: 100,
    },
    {
      title: "活动时间",
      search: false,
      render: (_, record) => {
        return `${record.activityStartTime} ~ ${record.activityEndTime}`;
      },
    },
    {
      title: "报名时间",
      search: false,
      render: (_, record) => {
        return `${record.signStartTime} ~ ${record.signEndTime}`;
      },
    },
    {
      title: "报名记录",
      search: false,
      render: (_, record) => {
        return renderRegisterRecordModal(record);
      },
    },
    {
      title: "上架状态",
      dataIndex: "status",
      valueType: "select",
      width: 150,
      fieldProps: {
        options: disableStatusOptions,
      },
    },
  ];

  const labelCol = {
    span: 3,
  };

  const actionRef = useRef();
  const [tabActiveKey, setTabActiveKey] = useState("1");

  const renderFormItem = ({ type, formRef }) => {
    return (
      <>
        {/* <ProFormRadio.Group
          labelCol={labelCol}
          label="展示位置"
          name="type"
          fieldProps={{
            options: typeNumOptions,
            fieldNames: {
              label: "tab",
              value: "key",
            },
          }}
        /> */}
        <ProFormText
          labelCol={labelCol}
          label="标题"
          name="title"
          rules={[
            { required: true, message: "请输入标题" },
            {
              max: 200,
              message: "最长为200位",
            },
          ]}
        />

        <ProFormTextArea
          labelCol={labelCol}
          fieldProps={{
            rows: 5,
          }}
          label="简介"
          name="content"
          rules={[
            { required: true, message: "请输入简介" },
            {
              max: 1000,
              message: "最长为1000位",
            },
          ]}
        />

        <ProForm.Item
          labelCol={labelCol}
          name="cover"
          label="封面"
          tooltip={
            tabActiveKey == 1
              ? "建议尺寸：702*320"
              : tabActiveKey == 2
              ? "建议尺寸：340*340"
              : "建议尺寸：208*208"
          }
          rules={[{ required: true, message: "请上传封面" }]}
        >
          <UploadFile />
        </ProForm.Item>
        <ProForm.Item
          name="detailImg"
          label="详情大图"
          tooltip="建议尺寸：750X750"
          labelCol={labelCol}
          rules={[{ required: true, message: "请上传封面" }]}
        >
          <UploadFile />
        </ProForm.Item>
        <ProFormDigit
          labelCol={labelCol}
          label="人数上限"
          name="limitNum"
          placeholder="请输入人数上限"
          min={1}
          rules={[{ required: true, message: "请输入人数上限" }]}
        />
        <ProFormDigit
          labelCol={labelCol}
          label="支付积分"
          name="consumePoints"
          placeholder="请输入报名支付积分"
          min={0}
        />
        <ProFormDigit
          labelCol={labelCol}
          label="获得积分"
          name="obtainPoints"
          placeholder="请输入报名获得积分"
          min={0}
        />

        <ProFormDateTimeRangePicker
          labelCol={labelCol}
          label="活动时间"
          tooltip="活动时间需在报名时间外"
          name="time"
          placeholder={["开始时间", "结束时间"]}
          fieldProps={{
            format: "YYYY-MM-DD HH:mm:ss",
            disabledDate: (current) => {
              return current && current <= moment().endOf("day") - 8.64e7;
            },
          }}
          transform={(values) => {
            return {
              activityStartTime: values ? values[0] : undefined,
              activityEndTime: values ? values[1] : undefined,
            };
          }}
          rules={[
            { required: true, message: "" },
            {
              validator: (_, value) => {
                const val = value?.filter(Boolean);
                if (!val?.length) {
                  return Promise.reject("请选择");
                }
                return Promise.resolve();
              },
            },
          ]}
        />

        <ProFormDateTimeRangePicker
          labelCol={labelCol}
          label="报名时间"
          tooltip="报名时间需在活动结束时间之前"
          name="time2"
          placeholder={["开始时间", "结束时间"]}
          fieldProps={{
            format: "YYYY-MM-DD HH:mm:ss",
            disabledDate: (current) => {
              return current && current <= moment().endOf("day") - 8.64e7;
            },
          }}
          transform={(values) => {
            return {
              signStartTime: values ? values[0] : undefined,
              signEndTime: values ? values[1] : undefined,
            };
          }}
          rules={[
            { required: true, message: "" },
            {
              validator: (_, value) => {
                const val = value?.filter(Boolean);
                if (!val?.length) {
                  return Promise.reject("请选择");
                }
                return Promise.resolve();
              },
            },
          ]}
        />

        <ProFormText
          labelCol={labelCol}
          label="活动地点"
          name="address"
          rules={[
            { required: true, message: "请输入活动地点" },
            {
              max: 200,
              message: "最长为200位",
            },
          ]}
        />

        <ProFormTextArea
          labelCol={labelCol}
          fieldProps={{
            rows: 5,
          }}
          label="温馨提示"
          name="reminder"
          rules={[
            { required: true, message: "请输入温馨提示" },
            {
              max: 1000,
              message: "最长为1000位",
            },
          ]}
        />
      </>
    );
  };

  const updateStatusFunc = async (record, actionRef, status) => {
    const postData = {
      id: record.id,
      status,
    };
    const res = await updateStatus(postData);
    if (res.data) {
      message.success("操作成功");
      actionRef?.current.reload();
    }
  };

  return (
    <PageContainer
      tabActiveKey={tabActiveKey}
      onTabChange={(key) => {
        setTabActiveKey(key);
        actionRef.current?.reload();
      }}
      tabList={typeNumOptions}
    >
      {useCommonTable({
        actionRef,
        title: "",
        columns,
        renderFormItem,
        modalWidth: 800,
        params: {
          type: tabActiveKey * 1,
        },
        fetchList,
        add,
        onFinish: async (fields, record, type, formRef, actionRefSelf) => {
          const postData = {
            ...fields,
            id: record?.id,
          };
          if (
            moment(postData.signStartTime).valueOf() >=
              moment(postData.activityEndTime).valueOf()
          ) {
            message.warning("报名时间需在活动结束时间之前");
            return;
          }

          if (
            moment(postData.signEndTime).valueOf() >
              moment(postData.activityEndTime).valueOf()
          ) {
            message.warning("报名时间需在活动结束时间之前");
            return;
          }
          let func = add;
          if (type === 2) {
            func = update;
          }
          const res = await func(postData);
          if (res.code == 200) {
            const modalTitle = type === 1 ? "新增" : "编辑";
            message.success(modalTitle + "成功");
            if (type === 1) {
              formRef.current?.resetFields();
            }
            actionRefSelf?.current.reload();
            return true; // 关闭弹框
          }
        },
        update,
        // remove,
        actionColumnWidth: 100,
        showCheckbox: false,
        layout: "horizontal",
        insertPosition: 0,
        renderOtherAction: (_, record, actionRef) => {
          // 活动结束后支持下架，不支持上架
          const over =
            new Date().getTime() >= new Date(record.activityEndTime).getTime();

          // manualOff=1表示已经下架过一次了，后续不支持再次上架
          return [
            record.status === 0 && record.manualOff == 0 && !over && (
              <Button
                type="primary"
                onClick={() => {
                  updateStatusFunc(record, actionRef, 1);
                }}
              >
                上架
              </Button>
            ),
            record.status === 1 && record.manualOff == 0 && (
              <Popconfirm
                key="delete"
                title="下架后不支持再次上架"
                onConfirm={() => updateStatusFunc(record, actionRef, 0)}
              >
                <Button type="primary" danger={true}>
                  下架
                </Button>
              </Popconfirm>
            ),
          ];
        },
        showEditBtnFunc: (_, record, actionRef) => {
          return record.status === 0 && record.manualOff == 0;
        },
        transformGetData: (record) => {
          return {
            ...record,
            time: [record?.activityStartTime, record?.activityEndTime],
            time2: [record?.signStartTime, record?.signEndTime],
          };
        },
        transformPostData: (values) => {
          return {
            ...values,
            type: tabActiveKey,
          };
        },
      })}
    </PageContainer>
  );
};
